package utils.load
{
	import asds.map.HashMap;
	
	import br.com.stimuli.loading.BulkLoader;
	import br.com.stimuli.loading.BulkProgressEvent;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.external.ExternalInterface;
	import flash.net.URLLoader;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.Dictionary;
	import flash.utils.clearInterval;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;

	/**
	 *  加载管理。
	 * @author 青竹
	 *
	 */
	public class LoaderManager
	{
        //private static const config:String="assList.xml";
        private static var count:int=0;
		private static var verDic:Dictionary
		public static var cache:HashMap=new HashMap();
		private static var callBackList:Vector.<Function>=new Vector.<Function>();
		private static var _eventHandle:EventDispatcher=new EventDispatcher();
		public static var rootUrl:String="";
		private static var _isIdle:Boolean;
		private static var mainVar:String="0";
		private static var timerId:int=-1;
		
		public function LoaderManager()
		{
		}
	   
		public static function setVarFile(dic:Dictionary,mainV:String):void{
			verDic=dic;
			mainVar=mainV;
		}
		private static var listLoaders:BulkLoader=new BulkLoader("beforehandLoad");
		public static function setBeforehandList(v:Vector.<String>):void{
			var count:int=0;
			var d:Dictionary = new Dictionary(true);
			var atxt:LoaderContext = new LoaderContext(false , ApplicationDomain.currentDomain);
			
			if (atxt.hasOwnProperty("allowLoadBytesCodeExecution")) {
				Object(atxt).allowLoadBytesCodeExecution = true;
			}
			if(atxt.hasOwnProperty("allowCodeImport"))
			{
				Object(atxt).allowCodeImport = true;
			}
			for(var i:int=0;i<v.length;i++){
				
				if(!d.hasOwnProperty(v[i])){
				    listLoaders.add(urlFormat(v[i]),{type:BulkLoader.TYPE_BINARY});
					d[v[i]] = 0;
					count++;
				}
			}
			trace("预加载项"+count);
			listLoaders.addEventListener(BulkProgressEvent.COMPLETE,onBeforehandCompleted);
			listLoaders.addEventListener( BulkLoader.ERROR,onBeforehandError);
			
			//listLoaders.addEventListener(BulkProgressEvent.PROGRESS,onPress);
		}
		private static function onBeforehandError(e:Event):void{
		    trace("预加载项错误",e)
		}
		protected static function onPress(event:BulkProgressEvent):void
		{
			//trace("预加载中..",event);
			trace("预加载中..",event.itemsLoaded+"/"+event.itemsTotal);
		}
		
		private static function onBeforehandCompleted(event:Event):void
		{
			listLoaders.removeEventListener(BulkProgressEvent.COMPLETE,onBeforehandCompleted);
			listLoaders.removeEventListener(BulkProgressEvent.PROGRESS,onPress);
			listLoaders=null ;
			trace("预加全部完成",event);
		}
		/**
		 * 是否闲置。
		 * @return
		 *
		 */
		public static function get isIdle():Boolean{
		    return _isIdle;
		}
		
		/**
		 * @param url
		 * @return
		 *
		 */
		public static function urlFormat(url:String):String{
			if(url==null) return null ;
			if(url.slice(0,4)=="http"){
				return url;
			}
			 if(verDic==null || !verDic.hasOwnProperty(url)){
				return rootUrl+url+"?v="+mainVar;
			 }
			
		     return rootUrl+url+"?v="+verDic[url];
		}
		
		/**
		 *
		 * @param task
		 *
		 */
		internal static function addTask(task:*):void{
			  if(task is Loader){
			  	  task.contentLoaderInfo.addEventListener(Event.COMPLETE,onCompleted);
			  	  task.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onError);
			  }else{
				  task.addEventListener(Event.COMPLETE,onCompleted);
				  task.addEventListener(IOErrorEvent.IO_ERROR,onError);
			  }
			  if(_isIdle){
				  if( listLoaders && listLoaders.itemsTotal>0){
					  listLoaders.pauseAll(); 
				  } 
				  trace("非空闲装态"); 
				  _isIdle=false;
			  } 
			  clearTimeout(timerId);
			  timerId=-1;
			  count++;
		}
		
		private static function onError(e:Event):void{
			  e.currentTarget.removeEventListener(Event.COMPLETE,onCompleted);
			  e.currentTarget.removeEventListener(IOErrorEvent.IO_ERROR,onError);
			  trace("LoaderManager加载错误:"+e);
			  count--;
			  if(count==0 && timerId<0){
				  timerId = setTimeout(call,2000);
				  //call();
			  }
		}
		
		private static function onCompleted(e:Event):void{
              e.currentTarget.removeEventListener(Event.COMPLETE,onCompleted);
			  e.currentTarget.removeEventListener(IOErrorEvent.IO_ERROR,onError);
			  count--;
			  if(count==0 && timerId<0){
				  timerId = setTimeout(call,2000);
				  //call();
			  }
		}
        private static function call():void{
			timerId=-1;
		     for(var i:int=0;i<callBackList.length;i++){
			    callBackList[i]();
			 }
			 _isIdle=true;
			 trace("=========空闲装态=========");
			 if(listLoaders && listLoaders.itemsTotal>0) {
				 listLoaders.resumeAll()
			 }
			
		}
			
		public static function addCallBack(fun:Function):void{
			if(callBackList.indexOf(fun)>=0) return;
			callBackList.push(fun);
		}
		public static function clearCallBack():void{
			callBackList=new Vector.<Function>();
		}
		/**
		 * 事件处理.
		 * @return
		 *
		 */
		public static function get eventHandle():EventDispatcher
		{
			return _eventHandle;
		}
	}
}